package com.example.shuiyin.service.impl;

import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
@Slf4j
public class LocalStorageServiceImpl implements StorageService {

    @Value("${storage.local.path}")
    private String storagePath;

    @Override
    public String store(MultipartFile file, String path) {
        try {
            if (file == null || file.isEmpty()) {
                throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
            }

            // 确保存储目录存在
            Path dirPath = Paths.get(storagePath, path);
            Files.createDirectories(dirPath);

            // 生成唯一文件名
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            Path targetPath = dirPath.resolve(newFilename);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            return targetPath.toString();
        } catch (IOException e) {
            log.error("文件存储失败: {}", e.getMessage(), e);
            throw new AppException("文件存储失败", ErrorCode.FILE_UPLOAD_ERROR);
        }
    }

    @Override
    public String getPreSignedUrl(String objectName) {
        // 本地存储不支持预签名URL，直接返回文件路径
        return Paths.get(storagePath, objectName).toString();
    }

    @Override
    public void delete(String objectName) {
        try {
            Path path = Paths.get(objectName);
            Files.deleteIfExists(path);
        } catch (IOException e) {
            log.error("删除文件失败: {}", e.getMessage(), e);
            throw new AppException("删除文件失败", ErrorCode.FILE_DELETE_ERROR, e);
        }
    }

    /**
     * 将文件加载为资源对象
     * 
     * @param filePath 文件路径
     * @return 资源对象
     */
    @Override
    public Resource loadFileAsResource(String filePath) {
        try {
            Path path = Paths.get(filePath);
            Resource resource = new FileSystemResource(path.toFile());
            
            if (resource.exists()) {
                return resource;
            } else {
                throw new AppException("文件不存在", ErrorCode.FILE_NOT_FOUND);
            }
        } catch (Exception e) {
            if (e instanceof AppException) {
                throw e;
            }
            log.error("加载文件资源失败: {}", e.getMessage(), e);
            throw new AppException("加载文件资源失败", ErrorCode.FILE_NOT_FOUND, e);
        }
    }

    @Override
    public String saveResult(String filePath, Long userId) {
        // 实现保存处理结果的逻辑
        try {
            Path sourcePath = Paths.get(filePath);
            
            // 创建用户目录
            Path userDir = Paths.get(storagePath, "results", userId.toString());
            Files.createDirectories(userDir);
            
            // 生成结果文件名
            String filename = UUID.randomUUID().toString() + 
                    sourcePath.getFileName().toString().substring(
                            sourcePath.getFileName().toString().lastIndexOf("."));
            
            // 复制文件到结果目录
            Path targetPath = userDir.resolve(filename);
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
            
            return targetPath.toString();
        } catch (IOException e) {
            log.error("保存处理结果失败: {}", e.getMessage(), e);
            throw new AppException("保存处理结果失败", ErrorCode.FILE_UPLOAD_ERROR, e);
        }
    }

    @Override
    public void deleteTempFile(String filePath) {
        try {
            Path path = Paths.get(filePath);
            Files.deleteIfExists(path);
        } catch (IOException e) {
            log.error("删除临时文件失败: {}", e.getMessage(), e);
            // 临时文件删除失败不抛出异常，仅记录日志
        }
    }

    @Override
    public String uploadFile(MultipartFile file, String objectName) throws IOException {
        if (file == null || file.isEmpty()) {
            throw new AppException("无效的文件", ErrorCode.INVALID_PARAMETER);
        }

        // 确保存储目录存在
        String dirPath = storagePath;
        if (objectName.contains("/")) {
            dirPath = storagePath + "/" + objectName.substring(0, objectName.lastIndexOf("/"));
        }
        
        Path directory = Paths.get(dirPath);
        Files.createDirectories(directory);
        
        // 保存文件
        Path targetPath = Paths.get(storagePath, objectName);
        Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回访问URL
        return "/uploads/" + objectName;
    }
    
    @Override
    public String uploadFile(String filePath, String fileName, String objectName) throws IOException {
        if (filePath == null || filePath.isEmpty()) {
            throw new AppException("无效的文件路径", ErrorCode.INVALID_PARAMETER);
        }

        // 确保存储目录存在
        String dirPath = storagePath;
        if (objectName.contains("/")) {
            dirPath = storagePath + "/" + objectName.substring(0, objectName.lastIndexOf("/"));
        }
        
        Path directory = Paths.get(dirPath);
        Files.createDirectories(directory);
        
        // 保存文件
        Path sourcePath = Paths.get(filePath);
        Path targetPath = Paths.get(storagePath, objectName);
        Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        
        // 返回访问URL
        return "/uploads/" + objectName;
    }
} 